<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ staffList.total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportStaff">导出</el-button>
          <el-button v-if="checkPermission('addEmployee')" size="small" type="primary" @click="dialogFormVisible=true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table v-loading="loading" border :data="staffList.rows">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="头像" prop="staffPhoto" width="180">
            <template #default="{row}">
              <img v-fiximg :src="row.staffPhoto" alt="" style="width: 180px; height: 120px" @click="showQrMa(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployee" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template #default="obj">
              {{ obj.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template #default="obj">
              <el-switch
                v-model="obj.row.enableState"
                active-value="1"
                inactive-value="2"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="250">
            <template #default="obj">
              <el-button type="text" size="small" @click="$router.push('/employees/details/'+obj.row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="authorityManagement(obj.row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delStaff(obj.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :page-size="paging.pageSize"
            layout="prev, pager, next"
            :total="staffList.total"
            :current-page="paging.page"
            @current-change="turnPage"
          />
        </el-row>
      </el-card>
      <!-- 表单 -->
      <el-dialog
        title="新增员工"
        :visible.sync="dialogFormVisible"
        width="40%"
        center
      >
        <el-form ref="form" :model="form" label-width="90px" label-position="left" :rules="rules">
          <el-form-item label="姓名" prop="username">
            <el-input v-model="form.username" />
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="form.mobile" />
          </el-form-item>
          <el-form-item label="聘用形式" prop="formOfEmployment">
            <el-select v-model="form.formOfEmployment" placeholder="请选择" style="width:100%">
              <el-option
                v-for="item in EnumEmployee.hireType"
                :key="item.id"
                :label="item.value"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="工号" prop="workNumber">
            <el-input v-model="form.workNumber" />
          </el-form-item>
          <el-form-item label="部门名称" prop="departmentName">
            <el-input v-model="form.departmentName" @focus="isShowTree = true" @blur="blurInput" />
            <el-tree v-if="isShowTree" :data="department" :props="{label:'name'}" default-expand-all class="departmentTree" @node-click="nodeClick" />
          </el-form-item>
          <el-form-item label="入职时间" prop="timeOfEntry">
            <el-date-picker v-model="form.timeOfEntry" type="date" placeholder="选择日期" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="转正时间" prop="correctionTime">
            <el-input v-model="form.correctionTime" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="btnCancel">取 消</el-button>
          <el-button type="primary" @click="btnOK">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="二维码"
        :visible.sync="qrIsShow"
        width="40%"
        center
      >
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <el-dialog
        title="权限管理"
        :visible.sync="authorityIsShow"
        width="40%"
        center
      >
        <el-checkbox-group v-model="checkList">
          <el-checkbox
            v-for="role in roleList"
            :key="role.id"
            :label="role.id"
            @change="reviseAuthority(authorityID)"
          >
            {{ role.name }}
          </el-checkbox>
        </el-checkbox-group>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getStaffAPI, delStaffAPI, addStaffAPI, assignRole } from '@/api/employees'
import { userDetails } from '@/api/user'
import { getRoleList } from '@/api/setting'
import { inquireDepartment } from '@/api/departments'
import { listToTreeData } from '@/utils'
import EnumEmployee from '@/api/constant/employees'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters'
import QRCode from 'qrcode'
export default {
  data() {
    return {
      loading: false,
      staffList: [],
      paging: {
        pageSize: 10,
        page: 1
      },
      dialogFormVisible: false,
      form: {
        username: '',
        mobile: '',
        formOfEmployment: '',
        workNumber: '',
        departmentName: '',
        timeOfEntry: '',
        correctionTime: ''
      },
      EnumEmployee,
      rules: {
        username: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
        ],
        formOfEmployment: [
          { required: true, message: '请输入聘用形式', trigger: 'blur' }
        ],
        workNumber: [
          { required: true, message: '请输入工号', trigger: 'blur' }
        ],
        departmentName: [
          { required: true, message: '请输入部门', trigger: 'blur' }
        ],
        timeOfEntry: [
          { required: true, message: '请输入入职时间', trigger: 'blur' }
        ],
        correctionTime: [
          { required: true, message: '请输入转正时间', trigger: 'blur' }
        ]
      },
      department: [],
      isShowTree: false,
      qrIsShow: false,
      authorityIsShow: false,
      checkList: [],
      roleList: [],
      authorityID: ''
    }
  },
  async created() {
    this.getStaff()
    const res = (await inquireDepartment()).depts
    this.department = await listToTreeData(res, '')
    const { rows } = await getRoleList()
    this.roleList = rows
  },
  methods: {
    // 获取员工数据
    async getStaff(data) {
      this.loading = true
      this.staffList = await getStaffAPI(data)
      this.loading = false
      this.staffList.rows.forEach(item => {
        item.enableState = String(Math.round(Math.random()) + 1)
      })
    },
    // 枚举聘用形式
    formatEmployee(row, col, cellVal) {
      // 将所有可能性, 逐个逐个列举出来的数据
      const obj = EnumEmployee.hireType.find(item => item.id === cellVal)
      return obj ? obj.value : '未知'
    },
    // 翻页
    turnPage(page) {
      this.paging.page = page
      this.getStaff(this.paging)
    },
    // 导出员工数据
    async exportStaff() {
      // 获取全部数据
      const res = (await getStaffAPI({ pageSize: this.staffList.total, page: 1 })).rows
      // 数据c处理
      const header = ['姓名', '手机号', '工号', '聘用形式', '入职时间']
      const data = res.map(item => {
        const lalala = EnumEmployee.hireType.find(val => Number(val.id) === Number(item.formOfEmployment))
        return [item.username, item.mobile, item.workNumber, lalala ? lalala.value : '未知', formatDate(item.timeOfEntry)]
      })
      await export_json_to_excel({ header, data })
    },
    // 删除员工
    async delStaff(id) {
      await this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await delStaffAPI(id)
      this.$message.success('删除成功')
    },
    // 部门选择失焦
    nodeClick(data) {
      this.form.departmentName = data.name
      this.$refs.form.validateField('departmentName')
      this.isShowTree = false
    },
    // 新增员工
    async btnOK() {
      // 校验表单
      await this.$refs.form.validate()
      // 发送请求
      await addStaffAPI(this.form)
      // 提示用户
      this.$message.success('添加成功')
      // 关闭弹窗
      this.btnCancel()
      // 更新页面
      this.$parent.getEmployeeList()
    },
    // 清理表单
    btnCancel() {
      // 清理表单
      this.form = {}
      // 清理报错
      this.$refs.form.resetFields()
      // 关闭弹窗
      this.dialogFormVisible = false
    },
    // 部门输入框失焦
    blurInput() {
      setTimeout(() => {
        this.isShowTree = false
      }, 200)
    },
    // 显示头像二维码
    showQrMa(url) {
      if (url) {
        this.qrIsShow = true
        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.myCanvas, url, {
            width: 300,
            color: {
              dark: '#66b1ff'
            }
          })
        })
      }
    },
    // 权限管理
    async authorityManagement(id) {
      this.checkList = (await userDetails(id)).roleIds
      this.authorityIsShow = true
      this.authorityID = id
    },
    // 修改权限
    async reviseAuthority(id) {
      await assignRole({ id, roleIds: this.checkList })
      this.$message.success('修改成功')
    },
    // 权限验证取值
    checkPermission(btnName) {
      const roles = this.$store.state.user.userInfo.roles
      return roles ? roles.points.includes(btnName) : false
    }
  }
}
</script>

<style lang="scss" scoped>
.departmentTree {
  width: 100%;
  border: 1px solid #888;
  position: absolute;
  height: 200px;
  z-index: 9;
  overflow: auto;
  }
</style>
